from flask import Flask, render_template, redirect, url_for, flash, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
import os

# 创建应用实例 - 明确指定模板目录
basedir = os.path.abspath(os.path.dirname(__file__))
template_path = os.path.join(basedir, 'app', 'templates')
static_path = os.path.join(basedir, 'app', 'static')

print(f"模板目录: {template_path}")
print(f"静态文件目录: {static_path}")

app = Flask(__name__, 
           template_folder=template_path,
           static_folder=static_path)

# 基础配置
app.config['SECRET_KEY'] = 'dev-key-please-change-in-production'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{os.path.join(basedir, "app.db")}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化扩展
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login_manager = LoginManager(app)
login_manager.login_view = 'login'
login_manager.login_message = '请先登录以访问此页面'

# ============ 简化模型定义 ============
class User(UserMixin, db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128))
    role = db.Column(db.String(20), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    is_active = db.Column(db.Boolean, default=True)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    
    def __repr__(self):
        return f'<User {self.username}>'

# ============ 登录管理器 ============
@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# ============ 路由定义 ============
@app.route('/')
def index():
    return render_template('index.html', title='首页')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        user = User.query.filter_by(username=username).first()
        
        if user and user.check_password(password) and user.is_active:
            login_user(user)
            flash('登录成功！', 'success')
            
            if user.role == 'student':
                return redirect(url_for('student_dashboard'))
            elif user.role == 'teacher':
                return redirect(url_for('teacher_dashboard'))
            elif user.role == 'enterprise':
                return redirect(url_for('enterprise_dashboard'))
            else:
                return redirect(url_for('index'))
        else:
            flash('用户名或密码错误', 'danger')
    
    return render_template('auth/login.html', title='登录')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')
        role = request.form.get('role')
        
        if password != confirm_password:
            flash('密码不匹配', 'danger')
            return redirect(url_for('register'))
        
        if User.query.filter_by(username=username).first():
            flash('用户名已存在', 'danger')
            return redirect(url_for('register'))
        
        if User.query.filter_by(email=email).first():
            flash('邮箱已存在', 'danger')
            return redirect(url_for('register'))
        
        # 创建用户（简化版，只保存基本信息）
        user = User(
            username=username,
            email=email,
            role=role
        )
        user.set_password(password)
        
        db.session.add(user)
        db.session.commit()
        
        flash('注册成功！请登录', 'success')
        return redirect(url_for('login'))
    
    return render_template('auth/register.html', title='注册')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    flash('您已成功退出登录', 'info')
    return redirect(url_for('index'))

@app.route('/student/dashboard')
@login_required
def student_dashboard():
    if current_user.role != 'student':
        flash('无权访问此页面', 'danger')
        return redirect(url_for('index'))
    return render_template('student/dashboard.html', title='学生仪表板')

@app.route('/teacher/dashboard')
@login_required
def teacher_dashboard():
    if current_user.role != 'teacher':
        flash('无权访问此页面', 'danger')
        return redirect(url_for('index'))
    return render_template('teacher/dashboard.html', title='教师仪表板')

@app.route('/enterprise/dashboard')
@login_required
def enterprise_dashboard():
    if current_user.role != 'enterprise':
        flash('无权访问此页面', 'danger')
        return redirect(url_for('index'))
    return render_template('enterprise/dashboard.html', title='企业仪表板')

# ============ 主程序入口 ============
if __name__ == '__main__':
    with app.app_context():
        # 确保所有表都已创建
        db.create_all()
        
        # 创建测试用户（如果不存在）
        if not User.query.filter_by(username='student1').first():
            print("创建测试用户...")
            
            users = [
                User(username='student1', email='student1@example.com', role='student'),
                User(username='teacher1', email='teacher1@example.com', role='teacher'),
                User(username='company1', email='company1@example.com', role='enterprise')
            ]
            
            for user in users:
                user.set_password('password123')
                db.session.add(user)
            
            db.session.commit()
            print('测试用户创建成功！')
    
    app.run(debug=True)